﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GGEditor.Core.Plugins;

namespace GGEditor.API.Samples.PluginTreeViewer
{
	public partial class PluginTreeView : UserControl
	{
		public PluginTreeView()
		{
			InitializeComponent();
			PluginManager.Instance.PluginAdded += OnPluginAddedOrRemoved;
			PluginManager.Instance.PluginRemoved += OnPluginAddedOrRemoved;
			OnPluginAddedOrRemoved(null);
		}

		void OnPluginAddedOrRemoved(IPlugin plugin)
		{
			treeView.Nodes.Clear();

			foreach (IPluginNode pluginNode in PluginManager.Instance.RootNode.Nodes)
				AddPluginNode(treeView.Nodes, pluginNode);
		}

		private void AddPluginNode(TreeNodeCollection nodes, IPluginNode pluginNode)
		{
			TreeNode treeNode = GetTreeNode(pluginNode, nodes);

			foreach (IPluginNode childPluginNode in pluginNode.Nodes)
			{
				AddPluginNode(treeNode.Nodes, childPluginNode);
			}
		}

		private TreeNode GetTreeNode(IPluginNode node, TreeNodeCollection nodes)
		{
			foreach (TreeNode treeNode in nodes)
			{
				if (treeNode.Text == node.Name)
					return treeNode;
			}

			TreeNode newNode = new PluginNodeTreeNode(node.Name);
			nodes.Add(newNode);
			return newNode;
		}

		class PluginNodeTreeNode : TreeNode
		{
			private string name;

			public PluginNodeTreeNode(string name)
			{
				this.name = name;
				Text = name;
				ContextMenuStrip = new ContextMenuStrip();
				ContextMenuStrip.ShowImageMargin = false;
			}
		}
	}
}
